#include "ArchivoDocumentos.h"

ArchivoDocumentos::ArchivoDocumentos(const char* filename):Archivo(filename) {
	string s1 = string(filename);
	string s2 = s1.substr(0, s1.length() - 4);
	s2 += ".ind";

	this->i = new IndiceDocumentos(s2.c_str());
}

void ArchivoDocumentos::setHeader(string pathRaiz) {
	char* s = new char[pathRaiz.length() + 1];
	strcpy(s, pathRaiz.c_str());

	unsigned short int numBytes = strlen(s);

	this->write((char*) &numBytes, sizeof(unsigned short int));
	this->write((char*) s, numBytes);
}

void ArchivoDocumentos::add(uint32_t nroDoc, string path) {
	RegistroDocumento r(nroDoc, path);
	i->add(nroDoc, (uint32_t) this->tellp());

	unsigned short int numBytes = sizeof(uint32_t) + path.length();
	this->write((char*) &numBytes, sizeof(unsigned short int));
	this->write((char*) &r, numBytes);
}

string ArchivoDocumentos::getPath(uint32_t nroDoc) {
	this->clear();

	this->seekg((unsigned)i->getOffset(nroDoc), ios::beg);

	unsigned short int numBytes;
	this->read((char*) &numBytes, sizeof(unsigned short int));

	RegistroDocumento r;
	this->read((char*) &r, numBytes);

	return r.getPath();
}

string ArchivoDocumentos::getPathRaiz() {
	this->clear();

	this->seekg(0, ios::beg);

	unsigned short int numBytes;
	this->read((char*) &numBytes, sizeof(unsigned short int));

	char* pathRaiz = new char[numBytes + 1];
	this->read((char*) pathRaiz, numBytes);
	pathRaiz[numBytes] = '\0';

	string s(pathRaiz);
	return s;
}

ArchivoDocumentos::~ArchivoDocumentos() {
	delete (this->i);
	this->close();
}
